$(function(){
	//页面初始化
	initPage();	
	
	$("#becomeFruit").hide();
	loadFileListZtree("");
	$(".widget-toolbar").on('click',"a:has(.icon-edit)",function(e){
		e.preventDefault();
		showModal($(this),$("#stepModen"));
	});
	
	
	//绑定附件上传组件
	Otod.file.init($("#comment-upload-doc")[0],{
		clickable:true,
		sending: function(file, xhr, formData){
			$("#file-active-comment").show();
			//var uuid = $("#taskModen input[name='uuid']").val();
			formData.append("busiId", $("#file-uuid").val());
		},
		success: function(file, data, e) {
			showFruitAttach();
			$("#file-active-comment").hide();
			document.getElementById("progress-doc").style.width = 0 + "%";
		},
		error: function(file, message){
			Otod.Msg.error(message.error);
			$("#file-active-comment").hide();
			document.getElementById("progress-doc").style.width = 0 + "%";
		},
		//进度条
		uploadprogress:function(file,progress, bytesSent) {
			
			document.getElementById("progress-doc").style.width = progress + "%";
		}
	});	
	
	
	//任务新增按钮点击事件
	$(".step-content").on('click','.task-add-span',function(e){
		var memberArray=null;
		var _this = $(this);
		Otod.ajax({
			url:ctx+"/pm/team/findByPrjId.do?prjId="+prjId,
			contentType: "application/x-www-form-urlencoded;",
			successFn:function(data){
				memberArray = data;
				createTaskAddWrap(_this.attr("key"),memberArray);
			}
		});
		
		return false;
	});
	
	
	
	//任务修改或查看
	$(".step-content").on('click',".task-item",function(e){
		e.preventDefault();
		editTask(this);
	});
	
	


	
	//阶段切换
	$("#wizard-steps").on("click","a",function(e){
		var p = $(this);
		var stepId = $(this).attr("stepId");
		$("#wizard-steps li").removeClass("editing");
		createTaskListWrap(GOBAL_PRJ_STEPLIST,null,stepId);
		loadFileListZtree(stepId);
	});
	
	//过滤条件
	$("#searchCond a").on("click",function(e){
		e.preventDefault();
		var p = $(this);
		var group = p.attr("group");
		var key = p.attr("key");
		$("#searchCond a[group="+group+"]").removeClass("selected");
		p.addClass("selected");
		
		var filter = new Array();
		$("#searchCond .selected").each(function(i){
			var p = $(this);
			var group = p.attr("group");
			var key = p.attr("key");
			filter.push({"group":group,"key":key});
		});
		var stepId = $("#wizard-steps .editing a").attr("stepId");
		createTaskListWrap(GOBAL_PRJ_STEPLIST,filter,stepId);
		
	});
	
	/*点击右边的任务*/
	$("#searchCondRight").on("click","#taskRight",function(e){
		p = $(this);
		p.addClass("selected");
		$("#selecctFruit").removeClass("selected");
		e.preventDefault();
		$("#becomeFruit").hide();
		$("#taskListRow").show();
	});
	/*点击右边的成果*/
	$("#searchCondRight").on("click","#selecctFruit",function(e){
		p = $(this);
		p.addClass("selected");
		$("#taskRight").removeClass("selected");
		e.preventDefault();
		$("#taskListRow").hide();
		$("#becomeFruit").show();
	});
	/*点击下载文档*/
	$("#comment-download-file").on("click",function(e){
		var fileId = $("#busitableKeyDoc").val();
		downloadFile(fileId);
	});
	/*点击提交审核*/
	$("#comment-submit-doc").on("click",function(btn){
		showModal(btn,"selectToMember");
		var fileId = $("#busitableKeyDoc").val();
	});
	/*点击审核通过*/
	$("#comment-audit-success").on("click",function(e){
		var fileId = $("#busitableKeyDoc").val();
		$("#audit-doc-form [name=docId]").val(prjId);		//初始化prjId
				//初始化prjId
		showModalFollowRight(e,"audit-doc");
		
		
	});
	
	//审核bu通过
	$("#audit-doc-btn-disAgree").on('click',function(){
		var fileId = $("#busitableKeyDoc").val();
		var comment = $("#audit-doc-form [name=comment]").val();
		var agree = "disAgree";
		Otod.ajax({
    		url:ctx +"/pm/comment/audit.do",
    		data: {prjId:fileId,comment:comment,agree:agree},
    		type:'GET',
    		successFn: function(data){
    			$('#audit-doc').modal('hide');
    			var treeObj = $.fn.zTree.getZTreeObj("projectTree");
    			var nodes = treeObj.getSelectedNodes();
    			if (nodes.length>0) {
    				nodes[0].status = "FAILURE";
    				treeObj.updateNode(nodes[0]);
    				$(".commentListForDoc").hide();
    			}
	    			Otod.Msg.info(data.info);
    			
    		}
    	 }); 
	});
	
	//审核通过
	$("#audit-doc-btn-agree").on('click',function(){
		var fileId = $("#busitableKeyDoc").val();
		var comment = $("#audit-doc-form [name=comment]").val();
		var agree = "agree";
		Otod.ajax({
			url:ctx +"/pm/comment/audit.do",
			data: {prjId:fileId,comment:comment,agree:agree},
			type:'GET',
			successFn: function(data){
				$('#audit-doc').modal('hide');
				var treeObj = $.fn.zTree.getZTreeObj("projectTree");
				var nodes = treeObj.getSelectedNodes();
				if (nodes.length>0) {
					nodes[0].status = "SUCCESS";
					treeObj.updateNode(nodes[0]);
					$(".commentListForDoc").hide();
				}
				Otod.Msg.info(data.info);
				
			}
		}); 
	});

	
	Otod.file.init();
	
});
/**
 * 页面初始化
 */
function initPage(){
	Otod.ajax({					
		url : ctx + "/pm/project/viewPrjInfo.do",
		data: prjId,
		successFn:function(data){
			$('#setPrjName').text(data.prjVo.prjName);
			$('#project-name').text(data.prjVo.prjName);
			changeStatus(data.prjVo.status,data.prjVo.endDate);
			GLOBAL_PRJTYPE = data.prjVo.prjType;		//产品类型
			GOBAL_PRJ_STEPLIST = data.stepList; 		//当前项目阶段
			GOBAL_PRJ_ROLE = data.prjRole;			//成员当前项目角色
			GLOBAL_PRJ = data.prjVo;				//项目信息
			createStepWizardWrap(data.stepList);
			createTaskListWrap(data.stepList);
			//renderStep(data.stepList);				//加载阶段
			renderMember(data.teamList);				//加载人员
			
			initAuth();
			initUserAuth();
		}
	});
	initEmpSelect(prjId);
	initEmpSelect2(prjId);
	$(".commentListForDoc").hide();
	//showModalFollowRight("","taskModen");
}

function initUserAuth(){
	$("#comment-upload-doc").css("display","none");
	if(GLOBAL_PRJ.status !="30090001"){//不是准备中项目
		$(".taskModen-btn-save").css("display","none");//任务详细内容设置
		$(".member-btn-control").css("display","none");//添加人员功能
		$(".audit-operation").css("display","none");//文档审核功能
		$(".submit-audit").css("display","none");//文档提交功能
		$(".begin-project-btn").css("display","none");//项目开始权限
		$(".show-project-btn").css("display","");//项目开始权限
		if(GLOBAL_PRJ.status =="30090002"){//进行中项目
			if(GOBAL_PRJ_ROLE=='30100002'){//负责人
				$(".submit-audit").css("display","");//文档提交功能
			}
			if(GOBAL_PRJ_ROLE != '30100003'){
				$(".audit-operation").css("display","");//文档审核功能
			}
		}
		if(GLOBAL_PRJ.status =="30090005"&&GOBAL_PRJ_ROLE=='30100002'){//提交审核项目，项目负责人
			
			$(".begin-project-btn").css("display","");//项目开始权限
		}
	}else{
		$(".taskModen-btn-save").css("display","none");//任务详细内容设置
		$(".member-btn-control").css("display","none");//添加人员功能
		$(".audit-operation").css("display","none");//文档审核功能
		$(".submit-audit").css("display","none");//文档提交功能
		$(".begin-project-btn").css("display","none");//项目开始权限
		if(GOBAL_PRJ_ROLE=='30100002'){//负责人
			$(".taskModen-btn-save").css("display","");//任务详细内容设置
			$(".member-btn-control").css("display","");//添加人员功能
		}
		
	}
	
	if(GOBAL_PRJ_ROLE =='30100007' ){//项目管理员
		if(GLOBAL_PRJ.status !='30090001'&&GLOBAL_PRJ.status !='30090004'){//不是准备中与结项的项目
			$(".taskModen-btn-save").css("display","");//任务详细内容设置
			$(".member-btn-control").css("display","");//添加人员功能
			$(".audit-operation").css("display","none");//文档审核功能
			$(".submit-audit").css("display","none");//文档提交功能
			$(".begin-project-btn").css("display","none");//项目开始权限
			$(".taskModen-btn-save").css("display","");//任务详细内容设置
			$(".member-btn-control").css("display","");//添加人员功能
		}else{
			$(".taskModen-btn-save").css("display","none");//任务详细内容设置
			$(".member-btn-control").css("display","none");//添加人员功能
			$(".audit-operation").css("display","none");//文档审核功能
			$(".submit-audit").css("display","none");//文档提交功能
			$(".begin-project-btn").css("display","none");//项目开始权限
			$(".taskModen-btn-save").css("display","none");//任务详细内容设置
			$(".member-btn-control").css("display","none");//添加人员功能
		}
	}
	
	
	
}



/*
 * 初始化权限
 */
function initAuth(){
	//$(".u-step .widget-header"). bg-white
	$(".task-item").each(function(i){
		var empNo = $(this).attr("empNo");
		if(GOBAL_CUST_NO == empNo){
			$(this).children(".item-list-status").addClass("bg-blue");
		}
	});
	
	$(".u-step").each(function(i){
		if($(this).attr("status") == "30050002"){	//进行中任务
			$(this).find(".widget-header").addClass("bg-white");
		}
	});
}

//显示弹出选项框
function showEditStepWin(){
	return false;
}

//开始项目
function beginProject(){
	
	Otod.Msg.confirm("确定要开始该项目吗？", "开始项目",function(){
		Otod.ajax({
			url:ctx+"/pm/project/beginProject.do",
			data:prjId,
			successFn:function(data){	

				
				Otod.Msg.info(data.info);
				//暂停一秒
				//setTimeout(refurbishPage(), 2000);
				//项目开始成功后刷新页面
				refurbishPage();
				
			}
		});
	});
}

//刷新页面
function refurbishPage() {
	location.reload();
}
function showProject(btn){
	Otod.ajax({					
		url : ctx + "/pm/comment/showComments.do",
		data: prjId,
		successFn:function(data){
			createComments(data);
			showModalFollowRight(btn,"audit-message");
		}
	});
	
}

function createComments(data){
	var commentMt = $('#auditMt').html();
	Mustache.parse(commentMt);
	var rendered = Mustache.render(commentMt, {
		data:	data
	});
	
	$('#comments').html(rendered);
}



//加载阶段
function loadStep(){
	Otod.ajax({					//查询已存在列表
		url : ctx + "/pm/step/list.do",
		data: prjId,
		successFn:function(data){
			renderStep(data);
		}
	});
}
//提交、审核、审核不通过
function submitAuditOperation(fileId,status){
	Otod.ajax({					
		url : ctx + "/sys/file/submitAuditOperation.do",
		data: {fileId:fileId,status:status},
		type:'get',
		successFn:function(data){
			Otod.Msg.info(data.info);
			
		}
	});
}


//新增step
function addStep(btn){
	resetStepModen();
	
	showModal(btn,"stepModen");
}


//重置step moden
function resetStepModen(){
	$("#stepModen-form")[0].reset();
	$("#stepModen-form [name=prjId]").val(prjId);		//初始化prjId
}

//显示modal
function showModal(btn,modal){
	var modalObj = getJqueryObj(modal);
	
	modalObj.modal();
	setModelFlowBtn(modalObj.children(".modal-dialog").get(0),btn);
}

//右侧显示modal
function showModalFollowRight(btn,modal){
	var modalObj = getJqueryObj(modal);
	
	modalObj.modal();
	setModelFollowRight(modalObj,"500px");
	$('.chosen-container-multi').css({'width':'270px','height':'30px'});
	
}

//显示modal
function showTpModal(modal){
	var modalObj = getJqueryObj(modal);
	modalObj.modal();
}


//重置step moden
function resetTaskModen(){
	$("#taskModen-form")[0].reset();
	$("#taskModen-form [name=prjId]").val(prjId);		//初始化prjId
}



/*小组件*******************************************/
/**
 * 生成阶段向导
 */
function createStepWizardWrap(data){
	var stepWizardMtp = $('#stepWizardMtp').html();
	Mustache.parse(stepWizardMtp);
	
	var rendered = Mustache.render(stepWizardMtp, {
		data:	data,
		stepStyle: function(){
			if(this.status == "30060003"){
				return "complete";
			}else if(this.status == "30060002"){
				return "active";
			}else{
				return "";
			}
		}
	});
	
	$('#wizard-steps').append(rendered);
}


/**
 * 生成任务列表
 * data  	阶段对象
 * curStep 	当前阶段
 */
function createTaskListWrap(data,filter,selectedStepId){
	var _stepVo;
	var selectedStep = null;
	
	if(data.length>0){								//默认第一个阶段为选中阶段
		selectedStep = data[0];
	}
	
	for(var i=0;i<data.length;i++){
		_stepVo = data[i];
		if(selectedStepId){
			if(_stepVo.uuid == selectedStepId){
				selectedStep = _stepVo;
				break;
			}
		}else{
			if(_stepVo.status == '30060002'){
				selectedStep = _stepVo;
				break;
			}
		}
	}
	
	if(selectedStep==null){		
		$('#taskListRow').html("");
		return;
	}

	$("#step-wizard-"+selectedStep.uuid).addClass("editing");
	
	
	var taskListMtp = $('#taskListMtp').html();
	Mustache.parse(taskListMtp);
	
	var taskItemMtp = $('#taskItemMtp').html();
	
	var rendered = Mustache.render(taskListMtp, {
		data:selectedStep,
		itemStatusStyle: function(){
			if(this.status == "30050002"){			//进行中
				return "blue";
			}else if(this.status == "30050003"){	//待确认
				return "orange";
			}else if(this.status == "30050004"){	//完成
				return "green";
			}else if(this.status == "30050005"){	//被退回
				return "red";
			}else{									//未开始
				return "";
			}
		},
		itemStatusName: function(){
			if(this.status == "30050002"){			//进行中
				return "进行中";
			}else if(this.status == "30050003"){	//待确认
				return "待确认";
			}else if(this.status == "30050004"){	//完成
				return "完成";
			}else if(this.status == "30050005"){	//被退回
				return "被退回";
			}else{									//未开始
				return "未开始"
			}
		},
		empNames: function(){
			var empNameList = this.empList;
			var empNamesList = "";
			if(this.empList.length>0){
				for(var i=0;i<empNameList.length;i++){
					empNamesList = empNamesList + empNameList[i].empName+",";
				}
				return  empNamesList.substring(0,empNamesList.length-1);
			}
		},
		
		filterFn:function(){
			var p = this;
			if(!filter){
				return true;
			}
			for(var i=0;i<filter.length;i++){
				var t = eval("p."+filter[i].group);
				if(filter[i].key != "" && filter[i].key != null && t != filter[i].key){
					return false;
				}
			}
			return true;
		}
	}, {taskItemLink:taskItemMtp});
	
	$('#taskListRow').html(rendered);
}

/**
 * 生成任务item的HTML
 */
function createTaskItemWrapHtml(itemData){
	var taskItemMtp = $('#taskItemMtp').html();
	Mustache.parse(taskItemMtp);
	$.extend(itemData,{itemStatusStyle: function(){
		if(this.status == "30050002"){			//进行中
			return "blue";
		}else if(this.status == "30050003"){	//待确认
			return "orange";
		}else if(this.status == "30050004"){	//完成
			return "green";
		}else if(this.status == "30050005"){		//被退回							
			return "red";
		}else{
			return ""; //未开始
		}
	},
	itemStatusName: function(){
		if(this.status == "30050002"){			//进行中
			return "进行中";
		}else if(this.status == "30050003"){	//待确认
			return "待确认";
		}else if(this.status == "30050004"){	//完成
			return "完成";
		}else if(this.status == "30050005"){   //被退回
			return "被退回";
		}else{									//未开始
			return "未开始";
		}
	}});
	var rendered = Mustache.render(taskItemMtp, itemData);
	return rendered;
}


//refresh task
function refreshTask(taskObj){
	var $taskItemPanel = $("#task-item-panel-"+taskObj.uuid);
	$(createTaskItemWrapHtml(taskObj)).insertAfter("#task-item-panel-"+taskObj.uuid);
	$taskItemPanel.remove();
}



/**
 * 查询项目文库 以菜单树的形式生成
 */
function loadFileListZtree(stepId){	
	Otod.ajax({
		url: ctx + '/pm/project/queryFruitByPrjId.do?prjId='+prjId+'&stepId='+stepId,
		type:"post",
		successFn : function(data){	
			for(var i = 0;i<data.length;i++){
				//文件夹						
				if(data[i].folderType=="40010001"){
					data[i].icon = ctx +"/static/images/folder.png";
				}else{
					data[i].icon=  ctx +"/static/images/file.png";
				}
			}
			//加载数据左边
			$.fn.zTree.init($("#projectTree"),setting,data);	
			var treeObj = $.fn.zTree.getZTreeObj("projectTree");
			treeObj.expandAll(true);
		}
	});
	
	$(".commentListForDoc").hide();
}

/**
 *  在线查看文件
 *  @param fileId 文件ID
 *  @param isFolder 是否为文件夹
 */
function clickFolderFn(fileId,showName,status){
	$(".commentListForDoc").show();
	$(".commentsdoclistdiv").show();
	$("#comment-upload-doc").css("display","");
	
	$("#file-uuid").val(fileId);
	//提交或审核成功
	showFruitAttach();
	$("#audit-doc-form [name=docName]").val(showName);
	if(GOBAL_PRJ_ROLE =="30100002"){
		$(".submit-audit").css("display","");
	}else{
		$(".submit-audit").css("display","none");
		
	}
	if(status !="SUCCESS"&&(GOBAL_PRJ_ROLE=="30100001"||GOBAL_PRJ_ROLE=="30100005"||GOBAL_PRJ_ROLE=='30100004'||GOBAL_PRJ_ROLE=='30100006')){
			$(".audit-operation").css("display","");
	}else{
		$(".audit-operation").css("display","none");
	}
	$("#busitableKeyDoc").val(fileId);
	initCommentListDoc(fileId);
	/*if(showName.indexOf('pdf') > 0){
		$("#busitableKeyDoc").val(fileId);
		initCommentListDoc(fileId);
		$("#showFruitDoc").attr("href",ctx+"/office/wordPDF/openPDF.do?fileName="+showName);
	}else{
		$("#busitableKeyDoc").val(fileId);
		initCommentListDoc(fileId);
		$("#showFruitDoc").attr("href",ctx+"/office/wordPDF/openWord.do?fileName="+showName);
		
	}*/
	
}

/**
 * 下载文件
 * @param fileId
 */
function downloadFile(fileId){
	Otod.file.download(fileId);
}

function changeStatus(status,endDate){
	if(status=="30090001"){
		$('#setprjStatus').text("准备中");
		$('#setprjStatus').css("color","grey");
	}else if(status=="30090002"){
		$('#setprjStatus').text(checkDate("进行中",endDate));
		$('#setprjStatus').css("color","blue");
	}else if(status=="30090003"){
		$('#setprjStatus').text("中止");
		$('#setprjStatus').css("color","red");
	}else if(status=="30090004"){
		$('#setprjStatus').text("结项");
		$('#setprjStatus').css("color","green");
	}else if(status=="30090005"){
		$('#setprjStatus').text("提交审核");
		$('#setprjStatus').css("color","brown");
	}
}

//日期控制状态显示
function checkDate(statusName,prjDate){
	var days = DateUtil.dateDiff('d', prjDate, new Date().getTime());//结果为正数（小，大）后面减前面
	if(days>-5&&days<=-3){
		//蓝色预警
		$('#setprjStatus').css("color","blue");
		return statusName+'(项目结束时间临近，请督促人员提交项目任务！)';
	}else if(days>-3&&days<=0){
		//黄色警告
		$('#setprjStatus').css("color","yellow");
		return statusName+'(项目马上到期,请尽快完成项目)';
	}else if(days>0&&days<=3){
		//红色警告
		$('#setprjStatus').css("color","red");
		return statusName+'(项目已超时'+days+'天)';
	}else if(days>3){
		//灰色停止
		$('#setprjStatus').css("color","gray");
		return statusName+'(项目已超时'+days+'天,项目已失效)';
	}else if(days<=-5){
		//正常绿色
		$('#setprjStatus').css("color","green");
		return statusName;
	}
	
}
